<?php
namespace app\manage\controller;
use my\MyRedis;
use  think\Db;
use traits\controller\Jump;

class Admin extends Base
{

    public function adminList() {
        $search = input('post.search','');
        $role = input('post.role','');
        $curr_page = input('post.pageIndex',1);
        $perpage = input('post.pageSize',10);
        $where = [
            ['a.del','=',0]
        ];
        if($search) {
            $where[] = ['a.username|a.realname','like',"%{$search}%"];
        }
        if($role) {
            $where[] = ['a.role','=',$role];
        }
        try {
            $count = Db::table('mp_admin')->alias('a')->where($where)->count();
            $list = Db::table('mp_admin')->alias('a')
                ->join('mp_auth_role r','a.role=r.id','left')
                ->where($where)
                ->order(['a.id'=>'DESC'])
                ->limit(($curr_page - 1)*$perpage,$perpage)
                ->field('a.id,a.username,a.realname,a.avatar,a.gender,a.status,a.role,a.del,r.title')
                ->select();
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'count' => $count,
            'list' => $list
        ];
        return ajax($ret);
    }

    public function adminAdd() {
        $post['username'] = input('post.username');
        $post['realname'] = input('post.realname');
        checkPost($post);
        $post['password'] = input('post.password');
        $post['role'] = input('post.role',0);
        $post['email'] = input('post.email','');
        $post['tel'] = input('post.tel','');
        $post['gender'] = input('post.gender',0);
        $post['status'] = input('post.status',1);
        $post['desc'] = input('post.desc');
        try {
            $where = [
                ['username','=',$post['username']]
            ];
            $exist = Db::table('mp_admin')->where($where)->find();
            if($exist) {
                return ajax('账号已存在',53);
            }
            if($post['password']) {
                $post['password'] = md5($post['password'].config('login_key'));
            }else {
               unset($post['password']);
            }
            Db::table('mp_admin')->insert($post);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function adminDetail() {
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            $whereUser = [
                ['id','=',$post['id']]
            ];
            $user_exist = Db::table('mp_admin')->where($whereUser)->find();
            if(!$user_exist) {
                return ajax('id',-4);
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($user_exist);
    }

    public function adminMod() {
        $post['username'] = input('post.username');
        $post['realname'] = input('post.realname');
        $post['id'] = input('post.id');
        checkPost($post);
        $post['password'] = input('post.password');
        $post['role'] = input('post.role',0);
        $post['email'] = input('post.email','');
        $post['tel'] = input('post.tel','');
        $post['gender'] = input('post.gender',0);
        $post['status'] = input('post.status',1);
        $post['desc'] = input('post.desc');
        if($post['username'] == 'root') {
            if($this->userinfo['admin_id'] !== 1) {
                return ajax('没有权限',54);
            }
        }
        try {
            $whereUser = [
                ['id','=',$post['id']]
            ];
            $user_exist = Db::table('mp_admin')->where($whereUser)->find();
            if(!$user_exist) {
                return ajax('id',-4);
            }
            $whereName = [
                ['username','=',$post['username']],
                ['id','<>',$post['id']]
            ];
            $exist = Db::table('mp_admin')->where($whereName)->find();
            if($exist) {
                return ajax('账号已存在',53);
            }
            if($post['password']) {
                $post['password'] = md5($post['password'].config('login_key'));
            }else {
                unset($post['password']);
            }
            Db::table('mp_admin')->where($whereUser)->update($post);
            Db::table('mp_admin_token')->where('admin_id','=',$post['id'])->update(['role'=>$post['role']]);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function adminDelete() {
        $post['id'] = input('post.id');
        checkPost($post);
        if($post['id'] == '1') {
            if($this->userinfo['admin_id'] !== 1) {
                return ajax('没有权限',54);
            }
        }
        try {
            $whereUser = [
                ['id','=',$post['id']]
            ];
            $user_exist = Db::table('mp_admin')->where($whereUser)->find();
            if(!$user_exist) {
                return ajax('id',-4);
            }
            Db::table('mp_admin')->where($whereUser)->update(['del'=>1]);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function adminBlock() {
        $post['id'] = input('post.id','');
        checkPost($post);
        try {
            $where = [
                ['id','=',$post['id']]
            ];
            if($post['id'] == '1') {
                if($this->userinfo['admin_id'] !== 1) {
                    return ajax('没有权限',54);
                }
            }
            $userinfo = Db::table('mp_admin')->where($where)->find();
            if(!$userinfo) {
                return ajax('id',-4);
            }
            if($userinfo['status'] === 1) {
                Db::table('mp_admin')->where($where)->update(['status'=>2]);
                Db::table('mp_admin_token')->where('admin_id','=',$userinfo['id'])->delete();
            }else {
                Db::table('mp_admin')->where($where)->update(['status'=>1]);
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function nodeList() {
        try {
            $list = Db::table('mp_auth_rule')->field('id,name,title,pid')->select();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($list);
    }

    public function nodeAdd() {
        $post['name'] = input('post.name');
        $post['title'] = input('post.title');
        checkPost($post);
        $post['pid'] = input('post.pid',0);
        try {
            $whereName = [
                ['pid','=',$post['pid']],
                ['name','=',$post['name']]
            ];
            $exist = Db::table('mp_auth_rule')->where($whereName)->find();
            if($exist) {
                return ajax('节点名已存在',56);
            }
            $id = Db::table('mp_auth_rule')->insertGetId($post);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax(['id'=>$id]);
    }

    public function nodeDelete() {
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            $whereNode = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_rule')->where($whereNode)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            if($exist['pid'] === 0) {
                Db::table('mp_auth_rule')->where('pid','=',$exist['id'])->delete();
            }
            Db::table('mp_auth_rule')->where('id','=',$exist['id'])->delete();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function nodeMod() {
        $post['id'] = input('post.id');
        $post['name'] = input('post.name');
        $post['title'] = input('post.title');
        checkPost($post);
        try {
            $whereNode = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_rule')->where($whereNode)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            $whereName = [
                ['id','<>',$post['id']],
                ['pid','=',$exist['pid']],
                ['name','=',$post['name']]
            ];
            $exist = Db::table('mp_auth_rule')->where($whereName)->find();
            if($exist) {
                return ajax('节点名已存在',56);
            }
            Db::table('mp_auth_rule')->where($whereNode)->update($post);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function roleList() {
        $where = [
            ['del','=',0]
        ];
        try {
            $count = Db::table('mp_auth_role')->where($where)->count();
            $list = Db::table('mp_auth_role')->where($where)
                ->order(['id'=>'DESC'])
                ->field('id,title,desc,status')
                ->select();
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'count' => $count,
            'list' => $list
        ];
        return ajax($ret);
    }

    public function roleDetail() {
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            $where = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_role')->where($where)->field('id,title,desc,status,rules,route')->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            $exist['menu_list'] = Db::table('mp_menu')->field('id,icon,title,path,pid')->select();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($exist);
    }

    public function roleAdd() {
        $post['title'] = input('post.title');
        $post['status'] = input('post.status');
        checkPost($post);
        $post['desc'] = input('post.desc');
        $rules = input('post.rules',[]);
        try {
            if(empty($rules)) {
                $post['rules'] = '';
                $post['rules_content'] = '';
            }else {
                $post['rules'] = implode(',',$rules);
                $whereNode = [
                    ['id','in',$rules]
                ];
                $nodeList = Db::table('mp_auth_rule')->where($whereNode)->column('name');
                $post['rules_content'] = implode(',',$nodeList);
            }
            Db::table('mp_auth_role')->insertGetId($post);
            $this->setRules();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function roleDelete() {
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            $where = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_role')->where($where)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            Db::table('mp_auth_role')->where($where)->update(['del'=>1]);
            $this->setRules();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function roleMod() {
        $post['id'] = input('post.id');
        $post['title'] = input('post.title');
        $post['status'] = input('post.status');
        checkPost($post);
        $post['desc'] = input('post.desc');
        $rules = input('post.rules',[]);
        try {
            $where = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_role')->where($where)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            if(empty($rules)) {
                $post['rules'] = '';
                $post['rules_content'] = '';
            }else {
                $post['rules'] = implode(',',$rules);
                $whereNode = [
                    ['id','in',$rules]
                ];
                $nodeList = Db::table('mp_auth_rule')->where($whereNode)->column('name');
                $post['rules_content'] = implode(',',$nodeList);
            }
            Db::table('mp_auth_role')->where($where)->update($post);
            $this->setRules();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function roleRouteMod() {
        $post['id'] = input('post.id');
        checkPost($post);
        $route = input('post.route',[]);

        try {
            $where = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_auth_role')->where($where)->find();
            if(!$exist) {
                return ajax('id',-4);
            }

            if(empty($route)) {
                $post['route'] = '';
                $post['route_content'] = json_encode([]);
            }else {
                $post['route'] = implode(',',$route);
                $whereRoute = [
                    ['id','in',$route]
                ];
                $post['route_content'] = $this->setRoute($whereRoute,$post['id']);
            }
            Db::table('mp_auth_role')->where($where)->update($post);
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function menuList() {
        try {
            $list = Db::table('mp_menu')->field('id,icon,title,path,pid')->order(['sort'=>'DESC','id'=>'ASC'])->select();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($list);
    }

    public function menuAdd() {
        $post['title'] = input('post.title');
        $post['path'] = input('post.path');
        checkPost($post);
        $post['icon'] = input('post.icon');
        $post['pid'] = input('post.pid',0);
        try {
            $id = Db::table('mp_menu')->insertGetId($post);
            $this->setRoute();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax(['id'=>$id]);
    }

    public function menuDelete() {
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            $whereNode = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_menu')->where($whereNode)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            if($exist['pid'] === 0) {
                Db::table('mp_menu')->where('pid','=',$exist['id'])->delete();
            }
            Db::table('mp_menu')->where('id','=',$exist['id'])->delete();
            $this->setRoute();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    public function menuMod() {
        $post['id'] = input('post.id');
        $post['title'] = input('post.title');
        $post['path'] = input('post.path');
        checkPost($post);
        $post['icon'] = input('post.icon');
        try {
            $whereNode = [
                ['id','=',$post['id']]
            ];
            $exist = Db::table('mp_menu')->where($whereNode)->find();
            if(!$exist) {
                return ajax('id',-4);
            }
            Db::table('mp_menu')->where($whereNode)->update($post);
            $this->setRoute();
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    private function setRules() {
        $redis = MyRedis::getInstance();
        $where = [
            ['del','=',0],
            ['status','=',1]
        ];
        $rolelist = Db::table('mp_auth_role')->where($where)->field('id,title,status,rules_content,route,route_content')->order(['id'=>'ASC'])->select();
//        $redis::flushDB();
        foreach ($rolelist as $role) {
            $rules = explode(',',$role['rules_content']);
            foreach ($rules as &$name) {
                $name = strtolower($name);
            }
//            $redis::getInstance()
            $data['status'] = $role['status'];
            $data['rules'] = $rules;
            $redis::set('role' . $role['id'],json_encode($data));
            if($role['route']) {
                $redis::set('route' . $role['id'],$role['route_content']);
            }
        }
        return true;
    }

    private function setRoute($whereRoute = [], $role='root') {
        $routeList = Db::table('mp_menu')->where($whereRoute)->field('id,title,path,icon,pid')->order(['sort'=>'DESC','id'=>'ASC'])->select();
        $new_arr = [];
        foreach ($routeList as $route) {
            if($route['pid'] === 0) {
                $subs = [];
                foreach ($routeList as $v) {
                    if($route['id'] == $v['pid']) {
                        $subs[] = $v;
                    }
                }
                $route['subs'] = $subs;
                $new_arr[] = $route;
            }
        }
        $route_content = json_encode($new_arr);
        $redis = MyRedis::getInstance();
        $redis::set('route'.$role,$route_content);
        return $route_content;
    }







}